package com.sunday.aomicaichang.ui.login;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.Areas;
import com.sunday.aomicaichang.model.Village;
import com.sunday.aomicaichang.service.LocationService;
import com.sunday.aomicaichang.ui.MainActivity;
import com.sunday.aomicaichang.ui.SelectAreaActivity;
import com.sunday.member.SessionToken;
import com.sunday.member.entity.Member;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

/**
 * Created by yun_sheng on 2017/5/31.
 */

public class RegisterThreeActivity extends BaseActivity {

    @Bind(R.id.tv_area)
    TextView tvArea;
    @Bind(R.id.btn_register)
    TextView btnRegister;
    @Bind(R.id.ly_register)
    RelativeLayout lyRegister;
    private String code, password, phone;

    private LocationService locationService;
    private LocationClient mClient;
    private int villageId=1 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register3);
        ButterKnife.bind(this);
        code = getIntent().getStringExtra("code");
        password = getIntent().getStringExtra("password");
        phone = getIntent().getStringExtra("phone");
        requestPermission();
    }

    @OnClick({R.id.ly_register, R.id.btn_register})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_register:
                //定位
                intent = new Intent(mContext, SelectAreaActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_register:
                Call<ResultDO<Member>> call = ApiClient.getApiAdapter().register(phone, password,
                        code, villageId);
                call.enqueue(new Callback<ResultDO<Member>>() {
                    @Override
                    public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                        dissMissDialog();
                        if (isFinish || response.body() == null) {
                            return;
                        }
                        ResultDO<Member> resultDO = response.body();
                        if (resultDO.getCode() == 0) {
                            SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                            BaseApp.getInstance().setMember(resultDO.getResult());
                            SessionToken.accountId = String.valueOf(resultDO.getResult().getId());
                            SessionToken.token = resultDO.getResult().getToken();
                            ToastUtils.showToast(mContext, "注册成功");
                            Intent intent = new Intent(mContext, MainActivity.class);
                            startActivity(intent);
                        } else {
                            ToastUtils.showToast(mContext, resultDO.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                        dissMissDialog();
                        ToastUtils.showToast(mContext, R.string.network_error);
                    }
                });
                break;
        }
    }

    private void requestLocation() {
        locationService = ((BaseApp) getApplication()).locationService;
        LocationClientOption mOption = locationService.getDefaultLocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mClient = new LocationClient(getApplicationContext());
        mClient.setLocOption(mOption);
        mClient.registerLocationListener(listener);
        mClient.start();
    }

    private void requestPermission() {
        LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        /*if(!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
           ToastUtils.showToast(mContext,"请打开位置开关");
        }*/
        PackageManager pkgManager = getPackageManager();
        //获取位置权限
        boolean locationWifiPermission = pkgManager.checkPermission(ACCESS_COARSE_LOCATION, getPackageName()) == PERMISSION_GRANTED;
        boolean locationGPSPermission = pkgManager.checkPermission(ACCESS_FINE_LOCATION, getPackageName()) == PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT >= 23 && !locationWifiPermission || !locationGPSPermission) {
            ActivityCompat.requestPermissions(this, new String[]{ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
            }, 0);
        } else {
            // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
            requestLocation();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0: {
                //If request is cancelled, the request arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
                    // SDK初始化，第三方程序启动时，都要进行SDK初始化工作
//                    PushManager.getInstance().initialize(this.getApplicationContext());
                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, ACCESS_COARSE_LOCATION)) {
                        ActivityCompat.requestPermissions(this, new String[]{ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION
                        }, 0);
                    } else {
                        showDialog();
                    }
                } else {
                    showDialog();
                }
                return;
            }
        }
    }

    private void showDialog() {
        final UIAlertView view = new UIAlertView(mContext, "温馨提示", "为了正常使用定位功能,请开启相关权限", "取消", "手动授权");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                Uri uri = Uri.parse("package:" + getPackageName());//包名
                Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                startActivity(intent);
                view.dismiss();
            }
        });
        view.show();
    }


    /***
     * 定位结果回调，在此方法中处理定位结果
     */
    BDLocationListener listener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub

            if (location != null &&location.getLocType() != BDLocation.TypeServerError) {
                Log.i(TAG, "定位成功");
                Log.i(TAG, "currentThread"+Thread.currentThread());
                mClient.stop();
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                SharePerferenceUtils.getIns(getApplicationContext()).putString("latitude", latitude);
                SharePerferenceUtils.getIns(getApplicationContext()).putString("longitude", longitude);
                getVillageList(latitude, longitude);
            }else {
                ToastUtils.showToast(mContext, "定位失败，请开启位置服务后重新定位");
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };

    private void getVillageList(String latitude,String longitude){
        showLoadingDialog(0);
        Call<ResultDO<List<Areas>>> call=ApiClient.getApiAdapter().getVillageByLocation(latitude,longitude);
        call.enqueue(new Callback<ResultDO<List<Areas>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Areas>>> call, Response<ResultDO<List<Areas>>> response) {
                if (isFinish||response.body()==null){return;}
                dissMissDialog();
                if (response.body().getCode()==0){
                    List<Areas> areasList=response.body().getResult();
                    if(areasList!=null&&areasList.size()>0){
                        tvArea.setText(areasList.get(0).getName());
                        villageId=areasList.get(0).getId();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Areas>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Village.ChildrenBeanX.ChildrenBean childrenBean = (Village.ChildrenBeanX.ChildrenBean) data.getSerializableExtra("area");
        if (childrenBean.getName() != null)
            tvArea.setText(childrenBean.getName());
        SharePerferenceUtils.getIns(mContext).putInt(ConstValue.AREA, childrenBean.getId());
        SharePerferenceUtils.getIns(mContext).putString(ConstValue.AREA_NAME, childrenBean.getName());

    }
}
